package service

import (
	"encoding/json"
	"ruoyi-go/app/admin/model/constants"
	"ruoyi-go/app/admin/model/system"
	"ruoyi-go/app/admin/model/tools"
	"ruoyi-go/pkg/cache/redisCache"
)

var SysDictCacheService = &sysDictCacheService{}

type sysDictCacheService struct{}

// InitDictCache 初始化数据字典到redis
func (service sysDictCacheService) InitDictCache() {
	var param = tools.SearchTableDataParam{
		Other: system.SysDictType{},
	}
	var typeResult = SysDictTypeService.SelectSysDictTypeList(param, false)
	var dataParam = tools.SearchTableDataParam{
		Other: system.SysDictData{},
	}
	dataResult := SysDictDataService.SelectDictDataList(dataParam, false)
	dictMap := make(map[string][]system.SysDictData)
	for _, dictData := range dataResult.Rows.([]system.SysDictData) {
		dictMap[dictData.DictType] = append(dictMap[dictData.DictType], dictData)
	}
	for _, dictType := range typeResult.Rows.([]system.SysDictType) {
		service.SetDictDataCache(dictType.DictType, dictMap[dictType.DictType])
	}

}

// RefreshDictDataCache 刷新某个字典类型的所有值
func (service sysDictCacheService) RefreshDictDataCache(dictType string) {
	dataResult := SysDictDataService.SelectDictDataByType(dictType)
	service.SetDictDataCache(dictType, dataResult)
}

// GetDictDataCacheByType 根据字典类型来获取字典数据
func (sysDictCacheService) GetDictDataCacheByType(dictType string) []system.SysDictData {
	dataJson, err := redisCache.RedisDB.Get(constants.SysDictCacheKey + dictType)
	if err != nil {
		return nil
	}
	var dictDataList []system.SysDictData
	err = json.Unmarshal([]byte(dataJson), &dictDataList)
	if err != nil || len(dictDataList) <= 0 {
		return nil
	}
	return dictDataList
}

// SetDictDataCache 设置字典类型 值
func (sysDictCacheService) SetDictDataCache(dictType string, dictDataList []system.SysDictData) {
	SysDictDataService.OrderByDictSortAsc(dictDataList)
	dataBytes, _ := json.Marshal(dictDataList)
	redisCache.RedisDB.Put(constants.SysDictCacheKey+dictType, string(dataBytes), -1)
}

// DeleteDictDataCache 删除字典
func (sysDictCacheService) DeleteDictDataCache(dictType string) {
	redisCache.RedisDB.Del(constants.SysDictCacheKey + dictType)

}

func (sysDictCacheService) DeleteAllDictCache() error {
	keys, _, err := redisCache.RedisDB.Scan(0, constants.SysDictCacheKey+"*", constants.ScanCountMax)
	if err != nil {
		return err
	}
	for _, key := range keys {
		redisCache.RedisDB.Del(key)
	}
	return nil
}
